package com.ludum.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.TimeUtils;
import com.ludum.game.controls.ControlManager;
import com.ludum.game.map.Map;
import com.ludum.game.player.Player;
import com.ludum.game.rendering.Camera2D;


public class ludumGame extends ApplicationAdapter {
	SpriteBatch batch;
	Texture img;
	Player player1;
	Player player2;
	ControlManager controlManager;
	Camera2D cam;
	Map map;
	long prevTime;

	private boolean isFinished;
	public static boolean endLevel = false;
	
	@Override
	public void create () {

		batch = new SpriteBatch();				
		isFinished = false;		

		initLevel();
		prevTime = TimeUtils.millis();
	}

	@Override
	public void render () {
		/* Update part */
		if(isFinished == false){
			if(endLevel == false){
				long timeSince = TimeUtils.timeSinceMillis(prevTime);
				prevTime = TimeUtils.millis();
		
				controlManager.checkInput();
				player1.update(timeSince/1000.f);
				player2.update(timeSince/1000.f);
				cam.update();
		
				if(Gdx.input.isKeyPressed(Keys.S))
				{
					Gdx.gl.glClearColor(1, 0, 0, 1);
				}
				else
				{
					Gdx.gl.glClearColor(0, 1, 0, 1);
				}
				/* Render part */
				Gdx.gl.glClearColor(0, 0, 0, 1);
				Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		
		
				batch.setProjectionMatrix(cam.getProj());
				batch.begin();
				{
					player1.draw(batch);
					player2.draw(batch);
					map.draw(batch);		
				}
				batch.end();
			}
			else {
				initLevel();
			}
		}
		else {
			//TODO draw the end
		}
	}
	
	private void createPlayers(){
		player1 = new Player(map.getSpawn1(),-1);
		player2 = new Player(map.getSpawn2(),1);
		controlManager = new ControlManager(player1,player2);	
		cam = new Camera2D(player1,player2);
	}
	
	private void initLevel(){
		map = LevelLoader.getLoader().next();
		
		if(map != null){
			createPlayers();
		}
		else {
			isFinished = true;
		}
	}
}
